package com.mti.epivisitemobile.medias
{
	import com.mti.epivisite.common.event.EventProxyBase;
	import com.mti.epivisitemobile.Constants;
	
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import spark.events.IndexChangeEvent;
	
	public class MediaListViewMediator extends Mediator
	{
		public static const NAME:String = "MediaListViewMediator";
		
		public function MediaListViewMediator(viewComponent:MediaListView)
		{
			super(NAME, viewComponent);
			
			proxy = EventProxyBase(facade.retrieveProxy(EventProxyBase.NAME));
			
			view.addEventListener(FlexEvent.CREATION_COMPLETE, onViewComplete);
		}
		
		private var proxy:EventProxyBase = null;
		
		private function onViewComplete(event:FlexEvent):void
		{
			view.removeEventListener(FlexEvent.CREATION_COMPLETE, onViewComplete);
			if (proxy.isLoaded == true)
			{
				if (proxy.baseEvent.pointList == null)
					proxy.getPoints(proxy.baseEvent);
				else
					updateView();
			}
		}
		
		override public function listNotificationInterests():Array
		{
			return [
				EventProxyBase.LOAD_SUCCESS,
				EventProxyBase.GET_POINTS_SUCCESS,
			];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch (notification.getName())
			{
				case EventProxyBase.LOAD_SUCCESS:
					proxy.getPoints(proxy.baseEvent);
					break;
				case EventProxyBase.GET_POINTS_SUCCESS:
					updateView();
					break;
			}
		}
		
		private function updateView():void
		{
			view.titleLabel.text = proxy.poi.title;
			view.description.text = proxy.poi.description;
			
			var text:Media = new Media();
			var image:Media = new Media();
			var video:Media = new Media();
			text.filename = "Description";
			text.url = "";
			image.filename = "Epita";
			image.type = "image";
			video.filename = "Pourquoi faire epita?";
			video.type = "video";
			medialist = new ArrayCollection();
			//medialist.addItem(text);
			medialist.addItem(image);
			//medialist.addItem(video);
			
			view.vlist.dataProvider = medialist;
			view.vlist.addEventListener(IndexChangeEvent.CHANGE, onListChange);
		}
		
		private function get view():MediaListView
		{
			return MediaListView(viewComponent);
		}
		
		private var medialist:ArrayCollection;
		
		private function onListChange(event:IndexChangeEvent):void
		{
			var selectedItem:Media = view.vlist.selectedItem as Media;
			if (!selectedItem)
			{
				return;
			}
			if (selectedItem.type == "text")
				sendNotification(Constants.SHOW_HTML);
			if (selectedItem.type == "image")
				sendNotification(Constants.SHOW_IMAGE);
			if (selectedItem.type == "video")
				sendNotification(Constants.SHOW_VIDEO);
		}
	}
}